JavaScript - detect webpage activity

Revision:


Content

navigator.userAgent detect activity / inactivity detect browser or tab closing


navigator.userAgent

top

Using the navigator userAgent property in JavaScript, one can get information about the user's device. It returns a string containing the user browser's name, version, operating system, etc.

syntax : navigator.userAgent

return type: e.g. Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36

The user agent can be easily tweaked with development tools and plugins. It is not 100% accurate and users can hide it for security purposes, or even change it to something else for testing.

detect browser - read the user agent

read the user agent

code:
                    <div>
                        <div id="browser"></div>
                    </div>
                    <style>
                        #browser{ display: block; width: 30vw; height: 5vw; background-color: skyblue;padding: 1vw;}
                    </style>
                    <script>
                        window.addEventListener("load", () => {
                            // CHROME
                            if (navigator.userAgent.indexOf("Chrome") != -1 ) {
                                console.log("Google Chrome");
                                document.getElementById("browser").innerHTML = "Google Chrome";
                            }
                            // FIREFOX
                            else if (navigator.userAgent.indexOf("Firefox") != -1 ) {
                                console.log("Mozilla Firefox");
                                document.getElementById("browser").innerHTML = "Mozilla Firefox";
                            }
                            // INTERNET EXPLORER
                            else if (navigator.userAgent.indexOf("MSIE") != -1 ) {
                                console.log("Internet Exploder");
                                document.getElementById("browser").innerHTML = "Internet Explorer";
                            }
                            // EDGE
                            else if (navigator.userAgent.indexOf("Edge") != -1 ) {
                                console.log("Internet Exploder");
                                document.getElementById("browser").innerHTML = "Internet Explorer";
                            }
                            // SAFARI
                            else if (navigator.userAgent.indexOf("Safari") != -1 ) {
                                console.log("Safari");
                                document.getElementById("browser").innerHTML = "Safari";
                            }
                            // OPERA
                            else if (navigator.userAgent.indexOf("Opera") != -1 ) {
                                console.log("Opera");
                                document.getElementById("browser").innerHTML = "Opera";
                            }
                            // YANDEX BROWSER
                            else if (navigator.userAgent.indexOf("YaBrowser") != -1 ) {
                                console.log("YaBrowser");
                                document.getElementById("browser").innerHTML = "YaBrowser";
                            }
                            // OTHERS
                            else {
                                console.log("Others");
                                document.getElementById("browser").innerHTML = "Others";
                            }
                        });
                    </script>
                

CSS prefix detection

prefix detection

code:
                <div>
                    <div id="prefix"></div>
                </div>
                <style>
                    #prefix{width: 20vw; height: 3vw; padding: 1vw; background-color:rgb(207, 211, 207);}
                </style>
                <script>
                    window.addEventListener("load", () => {
                    var prefix = (Array.prototype.slice
                    .call(window.getComputedStyle(document.documentElement, ""))
                    .join("") 
                    .match(/-(moz|webkit|ms)-/))[1];
            
                    // MOZ - FIREFOX (GECKO ENGINE)
                    // WEBKIT - CHROME, SAFARI, OPERA, EDGE (WEBKIT ENGINE)
                    // MS - OLD INTERNET EXPLORER & EDGE (TRIDENT ENGINE)
                    // NOTE - OLD OPERA VERSIONS USE PRESTO ENGINE. PREFIX IS -O
                    console.log(prefix);
                    document.getElementById('prefix').innerHTML = prefix;
                    });
                </script>
            

duck typing

Duck typing is simply detecting the “odd quirks” and “unique features” of each browser. For example, "window.opr" and "window.opera" is unique to Opera, and "window.chrome" is unique to Chrome. While this is probably one of the most reliable methods, it takes a lot of time to figure out what is unique to each browser.

duck typing

code:
                <div>
                    <div class="duck" id="duck1"></div>
                    <div class="duck" id="duck2"></div>
                    <div class="duck" id="duck3"></div>
                    <div class="duck" id="duck4"></div>
                    <div class="duck" id="duck5"></div>
                    <div class="duck" id="duck6"></div>
                    <div class="duck" id="duck7"></div>
                </div>
                <style>
                    .duck{width: 20vw; height: 1vh; padding: 0.8vw; background-color: orange;}
                </style>
                <script>
                    window.addEventListener("load", () => {
                    // OPERA 8.0+
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    // FIREFOX 1.0+
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    // SAFARI 3.0+
                    var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })
                    (!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
                    // INTERNET EXPLORER 6-11
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    // EDGE 20+
                    var isEdge = !isIE && !!window.StyleMedia;
                    // CHROME 1+
                    var isChrome = !!window.chrome;
                    // BLINK ENGINE DETECTION
                    var isBlink = (isChrome || isOpera) && !!window.CSS;
            
                    console.log("Opera - " + isOpera);
                    console.log("Firefox - " + isFirefox);
                    console.log("Safari - " + isSafari);
                    console.log("IE - " + isIE);
                    console.log("Edge - " + isEdge);
                    console.log("Chrome - " + isChrome);
                    console.log("Blink - " + isBlink);
                    document.getElementById("duck1").innerHTML = ("Opera - " + isOpera); 
                    document.getElementById("duck2").innerHTML = ("Firefox - " + isFirefox); 
                    document.getElementById("duck3").innerHTML = ("Safari - " + isSafari); 
                    document.getElementById("duck4").innerHTML = ("IE - " + isIE); 
                    document.getElementById("duck5").innerHTML = ("Edge - " + isEdge); 
                    document.getElementById("duck6").innerHTML = ("Chrome - " + isChrome); 
                    document.getElementById("duck7").innerHTML = ("Blink - " + isBlink); 
                    });
                </script>

            

detect whether opened on mobile device or desktop

opened on mobile or desktop?

code:
                <div>
                    <div id="detect"></div>
                </div>
                <script>
                    /* Storing user's device div in a variable*/
                    let div = navigator.userAgent;
                    /* Creating a regular expression  containing some mobile devices keywords to search it in div string*/
                    let regexp = /android|iphone|kindle|ipad/i;
                    /* Using test() method to search regexp in div it returns boolean value*/
                    let isMobileDevice = regexp.test(div);
                    if (isMobileDevice) {
                    console.log("You are using a Mobile Device");
                    document.getElementById("detect").innerHTML = "You are using a mobile device";
                    } else {
                        console.log("You are using Desktop");
                        document.getElementById("detect").innerHTML = "You are using Desktop";
                    }
                </script>
            


detect activity / inactivity

top

activity or not?

code:
                <div>
                    <div class="active" id="active1"></div>
                    <div class="active" id="active2"></div>
                    <div class="active" id="active3"></div>
                </div>
                <style>
                    .active{display: block; width: 30vw; height: 4vh; padding: 1vw; background-color: burlywood;}
                </style>
                <script>
                    function activityWatcher(){
                        //The number of seconds that have passed since the user was active.
                        var secondsSinceLastActivity = 0;
                        //Five minutes. 60 x 5 = 300 seconds.
                        var maxInactivity = (60 * 5);
                        //Setup the setInterval method to run every second. 1000 milliseconds = 1 second.
                        setInterval(function(){
                            secondsSinceLastActivity++;
                            console.log(secondsSinceLastActivity + ' seconds since the user was last active');
                            document.getElementById('active1').innerHTML = secondsSinceLastActivity + " seconds since the user was last active";
                                            //if the user has been inactive or idle for longer then the seconds specified in maxInactivity
                            if(secondsSinceLastActivity > maxInactivity){
                                console.log('User has been inactive for more than ' + maxInactivity + ' seconds');
                                document.getElementById('active2').innerHTML = "user has been inactive for more than " + maxInactivity + " seconds";
                                //Redirect them to your logout.php page.
                                location.href = 'logout.php';
                            }
                        }, 1000);
            
                        //The function that will be called whenever a user is active
                        function activity(){
                            //reset the secondsSinceLastActivity variable back to 0
                            secondsSinceLastActivity = 0;
                        }
                        //An array of DOM events that should be interpreted as user activity.
                        var activityEvents = [
                            'mousedown', 'mousemove', 'keydown',
                            'scroll', 'touchstart'
                        ];
                        //add these events to the document.
                        //register the activity function as the listener parameter.
                        activityEvents.forEach(function(eventName) {
                            document.addEventListener(eventName, activity, true);
                        });
                    }
                    activityWatcher();
                </script>
            


detect browser or tab closing

top

browser or tab closing?

This webpage

Detect browser or tab closing

The beforeunload function is triggered just before the browser or tab is to be closed or the page is to be reloaded. Modern browsers require some interaction with the page, otherwise the dialog box is not shown.

code:
                <div class="close">
                    <h4 style="color: green">This webpage</h4>
                    <p class="spec"><b>Detect browser or tab closing</b></p>
                    <p class="spec">The beforeunload function is triggered just before the browser or tab is to be closed or the page
                    is to be reloaded. Modern browsers require some interaction with the page, otherwise the dialog box is not shown.</p>
                    <form class="spec">
                        <textarea placeholder = "Trigger an interaction by writing something here"></textarea>
                    </form>
                </div>
                <script>
                    window.addEventListener('beforeunload', function (e) {
                        e.preventDefault();
                        e.returnValue = '';
                    });
                </script>